package br.org.nomoney.vink.util.servlet.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ByteArrayUtil {

	public static byte[] getByteArrayFromInput(int length, InputStream is)
			throws IOException {

		byte[] result = null;

		if (length > 0) {

			int readBytes = -1;

			byte[] buffer = new byte[length];
			ByteArrayOutputStream bout = new ByteArrayOutputStream(length);
			try {
				while ((readBytes = is.read(buffer, 0, length)) != -1) {
					bout.write(buffer, 0, readBytes);
				}
				bout.flush();

				result = bout.toByteArray();
			} finally {
				if (is != null) {
					is.close();
				}
				if (bout != null) {
					bout.close();
				}
			}
		}
		return result;
	}

	public static byte[] getByteArrayFromInput(InputStream in)
			throws IOException {

		ByteArrayOutputStream bout = null;
		byte[] result = null;

		// Read the request data
		try {
			int readBytes = -1;

			// TODO : no argument case!
			int length = in.available();
			if (length > 0) {
				byte[] buffer = new byte[length];
				bout = new ByteArrayOutputStream(length);
				while ((readBytes = in.read(buffer, 0, length)) != -1) {
					bout.write(buffer, 0, readBytes);
				}
				bout.flush();
				result = bout.toByteArray();
			}
		} finally {
			if (in != null) {
				in.close();
			}
			if (bout != null) {
				bout.close();
			}
		}
		return result;

	}

}
